﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows.Threading;
using PSE.Framework.ProviderLoader;
using PSE.Framework.ProviderLoader.Configuration;

namespace PSE.Framework.UI.Resources.Providers
{
    public class SmartClientResourceProvider : BaseProvider, IResourceProvider
    {
        private const string RESOURCEKEY_NOT_FOUND = "The resource key '{0}' could not be found.";

        public SmartClientResourceProvider(ProviderConfigurationElement configuration)
            : base(configuration)
        {
        }

        public object GetResource(object key, params object[] parameters)
        {
            if (key == null)
                throw new ArgumentNullException("key");
            if (parameters == null)
                throw new ArgumentNullException("parameters");

            object resource = System.Windows.Application.Current.FindResource(key);

            return string.Format((string)resource, parameters);
        }

        public object TryGetResource(object key, params object[] parameters)
        {
            if (parameters == null)
                throw new ArgumentNullException("parameters");

            object resource = null;

            if (key != null)
            {
                resource = System.Windows.Application.Current.TryFindResource(key);
            }

            if (resource != null)
            {
                return string.Format((string)resource, parameters);
            }
            else
            {
                return string.Format(RESOURCEKEY_NOT_FOUND, key);
            }
        }

        public bool ResourceExists(object key)
        {
            if (key == null)
                throw new ArgumentNullException("key");

            return (System.Windows.Application.Current.TryFindResource(key) != null);
        }

        public event EventHandler ResourceChanged;

        protected virtual void OnResourceChanged()
        {
            if (ResourceChanged != null)
                ResourceChanged(this, new EventArgs());
        }
    }
}